﻿using LCL.CodeEngine;
using LCL.CodeHelper;
using LCL.Config;
using LCL.Tools.Build;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace LCL.Tools.WinFrm
{
    public partial class FrmTemplateBatchCodeBuilder : BaseFrm
    {
        AppSetingInfo appSetingInfo = null;
        public FrmTemplateBatchCodeBuilder()
        {
            InitializeComponent();
            this.panel1.Visible = false;

            UIFactory.UIFact().BindDataBaseList(this.cmbDBlist);
            UIFactory.UIFact().BinTemplateTree(this.treeView1);

            this.label2.Text = "当前服务器：" + DbConfig.GetConfig().DbHost;
            appSetingInfo = AppSeting.GetConfig();
        }
        private void treeView1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                TempNode tempNode = (TempNode)this.treeView1.SelectedNode;
                string nodeID = tempNode.NodeID;
                string nodeType = tempNode.NodeType;
                string filePath = tempNode.FilePath;
                if (nodeType == "tt" || nodeType == "cmt")
                {
                    string text = filePath.Replace(AppDomain.CurrentDomain.BaseDirectory + "Template\\TemplateFile\\", "");
                    var newitem = new ListItem(filePath, text);
                    bool flg = true;
                    foreach (var iteml in this.listBox1.Items)
                    {
                        var ite = (ListItem)iteml;
                        if (ite.Text == newitem.Text)
                        {
                            flg = false;
                            break;
                        }
                    }
                    if (flg)
                    {
                        this.listBox1.Items.Add(newitem);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("加载模板失败", ex);
            }
        }
        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            this.listBox1.Items.Remove(this.listBox1.SelectedItem);
        }
        private void but_expCode_Click(object sender, EventArgs e)
        {
            this.but_expCode.Enabled = false;
            this.panel1.Visible = true;
            string dbName= this.cmbDBlist.Text;
            var tables = UIFactory.UIDb().GetTables(dbName);
            this.progressBar1.Maximum = tables.Count;
            this.progressBar2.Maximum = this.listBox1.Items.Count;
            for (int i = 0; i < this.listBox1.Items.Count; i++)
            {
                this.progressBar2.Step = 1;
                this.progressBar2.Value = i;
                var item = (ListItem)this.listBox1.Items[i];
                string tempfile = item.Value;
                string tempname = Path.GetFileNameWithoutExtension(tempfile);
                string dir = CodeCommon.DesktopDirectory;
                dir = dir + @"\";
                #region MyRegion
                CodeInfo codeinfo;
                for (int j = 0; j < tables.Count; j++)
                {
                    var table = tables[j];
                    string strContent = "";
                    codeinfo = new CodeInfo();
                    try
                    {
                        BuilderTemp builderTemp = new BuilderTemp(dbName, table.TableName, tempfile, "table");
                        codeinfo = builderTemp.GetCode();
                        if (codeinfo.ErrorMsg != null && codeinfo.ErrorMsg.Length > 0)
                        {
                            strContent = string.Concat(new string[]{codeinfo.Code,Environment.NewLine,
                                "/*----------代码生成时出现错误:------",Environment.NewLine,codeinfo.ErrorMsg,"*/"});
                        }
                        else
                        {
                            strContent = codeinfo.Code;
                        }
                    }
                    catch (Exception ex)
                    {
                        strContent = string.Concat(new string[]{codeinfo.Code,Environment.NewLine,
                                "/*----------代码生成时出现错误:------",Environment.NewLine,ex.Message,"*/"});
                        continue;
                    }
                    string filename = getfilePath(dir, codeinfo.FileExtension, table.TableName);
                    CodeCommon.CreateFiles(filename, strContent);
                    this.progressBar1.Step = 1;
                    this.progressBar1.Value = j;
                }
                #endregion
            }
            this.panel1.Visible = false;
            this.but_expCode.Enabled = true;
        }
        private string getfilePath(string dir,string ext,string tableName)
        {
            string filename = "";
            if (ext.StartsWith("."))
            {
                int num = ext.Split('.').Length - 1;
                if (num > 1)
                {
                    //{namespace}/views/{tablename}/index.php
                    string str = ext;
                    str = str.Replace("{namespace}", appSetingInfo.NameSpace)
                            .Replace("{tablename}", Utility.GetClassName(tableName))
                            .Replace("{_tablename}", Utility.GetClassName(tableName));
                    filename = dir + str.Substring(1);
                }
                else
                {
                    filename = dir + Utility.GetClassName(tableName) + ext;
                }
            }
            else
            {
                filename = dir + Utility.GetClassName(tableName, true) + "." + ext;
            }
            return filename;
        }
    }

    /// <summary>
    /// ComboBox的项
    /// </summary>
    public class ListItem : System.Object
    {
        /// <summary>
        /// 值
        /// </summary>
        public string Value { get; set; }
        /// <summary>
        /// 显示的文本
        /// </summary>
        public string Text { get; set; }

        public ListItem(string value, string text)
        {
            this.Value = value;
            this.Text = text;
        }
        public override string ToString()
        {
            return this.Text;
        }
    }
}
